package com.zoe.shardingjdbc.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/17
 * @Description 数据库精确查询算法 - 具体某个值的查询
 */
public class MyPreciseDBShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * @param collection           表示可选的数据源值 - 这里对应的数据库别名集合
     * @param preciseShardingValue 分片键对应的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        Long value = preciseShardingValue.getValue();
        BigInteger bigInteger = Convert.toBigInteger(value);
        BigInteger add = bigInteger.mod(Convert.toBigInteger(2)).add(Convert.toBigInteger(1));
        // 拼接成数据库的名称
        String DBName = StrUtil.format("m{}", add);
        if (collection.contains(DBName)) {
            return DBName;
        }
        throw new RuntimeException("不存在的数据包");
    }
}
